package ensemble.samples.custom.sqlformat.javafx.util;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.date.TimeInterval;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.support.ExcelTypeEnum;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.opencsv.CSVReader;
import com.opencsv.CSVReaderBuilder;

/**
 * @author duanxq
 * @date 2022/2/24
 */
public class CsvUtils {

    public static void csv2Excel(List<String> pathList) throws Exception {
        TimeInterval timer = new TimeInterval();
        for (int i = 0, pathListSize = pathList.size(); i < pathListSize; i++) {
            final String p = pathList.get(i);
            timer.start(String.valueOf(i));
            AppContext.contentOutAppend(p);
            String fileName = p + ".xlsx";
            ExcelWriter excelWriter = EasyExcel.write(fileName)
                .excelType(ExcelTypeEnum.XLSX).build();
            WriteSheet writeSheet = EasyExcel.writerSheet().head(head()).sheetName("data").build();
            int count = 0;
            int size = 10000;
            List<List<String>> tmp = new ArrayList<>(size);
            try (CSVReader csvReader = new CSVReaderBuilder(new BufferedReader(new InputStreamReader(new FileInputStream(
                p), StandardCharsets.UTF_8))).build()) {
                for (String[] s : csvReader) {
                    count++;
                    tmp.add(array2List(s));
                    if (tmp.size() >= size) {
                        // 写excel 文件流会自动关闭
                        excelWriter.write(tmp, writeSheet);
                        AppContext.contentOutAppend(String.valueOf(count));
                        tmp.clear();
                    }
                }
            }
            AppContext.contentOutAppend(String.valueOf(count));
            excelWriter.write(tmp, writeSheet);
            excelWriter.finish();
            AppContext.contentOutAppend(String.format("transfer success. cost %ss",
                timer.intervalSecond(String.valueOf(i))));
            AppContext.contentOutAppend(String.format("file: [%s]", fileName));
        }
    }

    private static List<List<String>> head() {
        return new ArrayList<>();
    }

    private static List<String> array2List(String[] strings) {
        return Arrays.stream(strings).collect(Collectors.toList());
    }

}
